package com.study.GameService.NetConnection;


import com.study.Caro.Brain;

import android.os.Handler;
import android.os.Message;

public class GameService {
	public static int SERVER_MODE = 0;
	public static int CLIENT_MODE = 1;
	private int play_mode;
	private Handler mReceiver;
	
	private ServerThread serverThread;
	private ClientThread clientThread;
	private String mServerIP;
	
	private static GameService instance = null; // Singleton instance
	
	protected GameService()
	{
	}

	public static GameService GetInstance(int mode, String serverIP){
		if(instance == null){
			instance = new GameService();
			instance.play_mode = mode;
			instance.mServerIP = serverIP;
		}
		return instance;
	}
	
	public void SetReceiver(Handler receiver)
	{
		mReceiver = receiver;
	}
	
	public static void SendDataBack(Message msg){
		if(instance == null)
			return;
		instance.mReceiver.sendMessage(msg);
	}
	
	public int GameStart(){
		int ret = 0;
		if(instance == null)
			ret = 0;
		if(play_mode == SERVER_MODE){
			serverThread = new ServerThread(mReceiver);
			if(serverThread != null){
				serverThread.start();
				ret = 1;
			}
		}else if(play_mode == CLIENT_MODE){
			clientThread = new ClientThread(mReceiver, mServerIP);
			if(clientThread != null){
				clientThread.start();
				ret = 1;
			}
		}
		return ret;
	}
	
	private static Handler ownHandler = new Handler(){
		public void handleMessage(Message msg){
			if(instance == null)
				return;
			if(instance.play_mode == GameService.SERVER_MODE)
				instance.serverThread.handleMessage(msg);
			else
				instance.clientThread.handleMessage(msg);
		}
	};
	
	public static void SendData(Message msg)
	{
		ownHandler.sendMessage(msg);
	}
	
	public void QuitGame(){
		if(play_mode == SERVER_MODE){
			serverThread.CloseConnection();
		}else if(play_mode == CLIENT_MODE){
			clientThread.CloseConnection();
		}
		Brain.GetInstance().Reset();
	}
	public static int GetMode(){
		if(instance == null)
			return -1; // invalid calling
		return instance.play_mode;
	}
}
